import React, { useCallback, useEffect, useState } from "react";
import { View, Text, ScrollView } from "@tarojs/components";

import "./index.module.scss";
import tools from "@/common/tools";
import { airportCityListReq } from "@/common/api";
import { ERR_MES } from "@/common/constant";
import { CityItem } from "./components/CityItem";

const Index = () => {
  const [cityListObj, setCityListObj] = useState({}); // 处理之后的城市列表
  const [letterList, setLetterList] = useState<string[]>([]); // 字母列表
  const [currentLetter, setCurrentLetter] = useState(""); // 当前选中的字母

  const formatList = (list: any[]) => {
    // obj = {
    //   A: [
    //     {},
    //     {}
    //   ],
    //   B: [

    //   ]
    // }
    const obj = {};
    if (list?.length) {
      list.map((ele) => {
        const { first_letter } = ele;
        // 判断obj中是否有以first_letter为键的属性
        if (!obj[first_letter]) {
          obj[first_letter] = [];
        }
        obj[first_letter].push(ele);
      });
    }
    return obj;
  };

  const getCityList = useCallback(async () => {
    tools.showLoading();
    try {
      const res: any = await airportCityListReq({});
      console.log("res: ", res);
      if (res.code === 1) {
        const obj = formatList(res.result);
        setCityListObj(obj);
        setLetterList(Object.keys(obj));
        console.log("obj: ", obj);
        console.log("Object.keys(obj): ", Object.keys(obj));
      }
    } catch (error) {
      tools.showToast(ERR_MES);
    } finally {
      tools.hideLoading();
    }
  }, []);

  const onLetterClick = (letter) => {
    setCurrentLetter(letter);
  };

  useEffect(() => {
    getCityList();
  }, [getCityList]);

  return (
    <View className="airport-list-container">
      <ScrollView
        scrollY
        scrollWithAnimation={tools.isAliPay ? false : true}
        style={{ height: "100vh" }}
        scrollIntoView={currentLetter}
      >
        {letterList?.map((item) => {
          const cityList = cityListObj[item];
          return <CityItem key={item} label={item} cityList={cityList} />;
        })}
      </ScrollView>
      <View className="letter-container">
        {letterList?.map((item) => (
          <View
            key={item}
            className="letter-item"
            onClick={() => onLetterClick(item)}
          >
            {item}
          </View>
        ))}
      </View>
    </View>
  );
};

export default Index;
